<?php

namespace app\api\controller;

use AliPay\App;
use app\api\model\DaoVipDetail;
use app\api\model\Userr;
use think\admin\Controller;
use think\admin\model\SystemConfig;

/**
 * 异步通知处理
 * Class Notify
 * @package app\data\controller\api
 */
class Notify extends Controller
{
    /**
     * 支付宝支付通知
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function alipay()
    {
        $config = config('pay');
        try {
            $post_data = App::instance($config['alipay_config'])->notify();
            if ($post_data['trade_status'] == 'TRADE_SUCCESS') {
                sysoplog('支付宝支付成功', json_encode($post_data));
                get_order_info($post_data['out_trade_no'], $post_data['auth_no']);
            }
        } catch (\Exception $e) {
            sysoplog('alipay catch', $e->getMessage());
        }
        return 'success';
    }

    /**
     * http://dadao.36i.cn/api/notify/wxpay
     * @return void
     */
    public function wxpay()
    {
        try {
            $wx_config = SystemConfig::mk()->where(['type' => 'wechat'])->column('value', 'name');
            $wx_config = [
                'appid' => $wx_config['appid'],
                // 配置商户支付参数（可选，在使用支付功能时需要）
                'mch_id' => $wx_config['mch_id'],
                'mch_v3_key' => $wx_config['mch_v3_key']
            ];
            $wechat = \WeChat\Pay::instance($wx_config);
            // 4. 获取通知参数
            $data = $wechat->getNotify();
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 去更新下原订单的支付状态
                sysoplog('微信支付成功', json_encode($data));
                get_order_info($data['out_trade_no'], $data['transaction_id']);
                // 返回接收成功的回复
                ob_clean();
                echo $wechat->getNotifySuccessReply();
            }

        } catch (\Exception $e) {

            // 出错啦，处理下吧
            sysoplog('微信支付失败', $e->getMessage());
            echo $e->getMessage() . PHP_EOL;
        }
    }

    /**
     * 苹果支付
     * http://dadao.36i.cn/api/notify/iospay
     * @return void
     */
    public function iospay()
    {
        $data = $this->_vali([
            'username.require' => '缺少用户名~',
            'orderId.require' => '缺少订单ID~',
            'receipt.require' => '缺少票据~',
            'identifier.require' => '缺少交易唯一标识~',
        ]);
        // 请求验证
        $result = $this->iosVerifyTickets($data['receipt']);
        // 如果是沙盒数据 则验证沙盒模式
        if ($result['status'] == 21007) {
            $result = $this->iosVerifyTickets($data['receipt'], true);
        }
        sysoplog('苹果支付参数', json_encode($data));
        sysoplog('苹果支付成功', json_encode($result));
        if ($result['status'] == 0 && $result['receipt']['bundle_id'] == 'com.dadao.ios') {
            get_order_info($data['orderId'], $data['identifier']);
            $this->success('获取成功', ['code' => 1]);
        } else {
            $this->success('获取失败', ['code' => -1]);
        }
    }


    /**
     * ios验证票据
     * @param string $receipt
     * @param false $sandbox
     * @return array|int|mixed
     * @throws Exception
     */
    protected function iosVerifyTickets(string $receipt, bool $sandbox = false)
    {
        if ($sandbox) {
            $url = 'https://sandbox.itunes.apple.com/verifyReceipt'; // 测试环境
        } else {
            $url = 'https://buy.itunes.apple.com/verifyReceipt'; // 正式环境
        }
        $params = json_encode(["receipt-data" => $receipt]);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($curl);
        $errno = curl_errno($curl);
        curl_close($curl);
        $data = json_decode($data, true);
        if (!is_array($data)) { // 开发过程中经常遇到curl 35错误码，或者28超时
            return $errno;
        }
        return $data;
    }


}